<template>
  <div>
    <van-address-edit :area-list="areaList" show-postal show-delete show-set-default
                      :area-columns-placeholder="['请选择', '请选择', '请选择']" @save="handleSave" @delete="handleDelete"
                      :address-info="addressInfo"/>
  </div>

</template>

<script>
import {
  areaList
} from "@vant/area-data";

import * as AddressAPI from "@/api/address.js";

export default {
  data() {
    return {
      areaList, //标准的地区列表
      addressInfo: {
        //收货人信息初始值
        id: "", //每条地址的唯一标识
        name: "", //姓名
        tel: "", //电话
        province: "", //省份
        city: "", //城市
        county: "", //区县
        areaCode: "", //地区编码，通过省市区选择获取（必填）
        postalCode: "", //邮政编码
        addressDetail: "", //详细地址
        isDefault: false, //是否选择默认
      }
    };
  },

  props: {
    id: {
      type: [Number, String],
    }
  },

  created() {
    this.getAddressDetail();

  },
  methods: {
    getAddressDetail() {
      if (this.id) {
        AddressAPI.getDetailById(this.id).then(result => {
          //数据结构参见Vant官网 和 API文档
          this.addressInfo.id = result.data.id;
          this.addressInfo.name = result.data.name;
          this.addressInfo.tel = result.data.tel;
          this.addressInfo.province = result.data.province;
          this.addressInfo.city = result.data.city;
          this.addressInfo.county = result.data.county;
          this.addressInfo.areaCode = result.data.areaCode; //
          this.addressInfo.postalCode = result.data.postalCode; //
          this.addressInfo.addressDetail = result.data.addressDetail; //
          this.addressInfo.isDefault = result.data.isDefault; //
        });
      }
    },

    //处理保存地址
    handleSave(content) {
      //准备参数
      let params = {
        id: content.id,
        name: content.name,
        tel: content.tel,
        province: content.province,
        city: content.city,
        county: content.county,
        areaCode: content.areaCode, //
        postalCode: content.postalCode, //
        addressDetail: content.addressDetail, //
        isDefault: content.isDefault, //
      };

      AddressAPI.save(params).then(result => {
        this.$toast(result.message);
        //页面跳转 上一页面
        setTimeout(() => {
          this.$router.go(-1);
        }, 1000);
      })
    },

    // 处理删除地址
    handleDelete(content) {
      let id = content.id;
      if (!id) return;

      AddressAPI.deleteById(id).then(result => {
        this.$toast(result.message);
        //页面跳转 上一页面
        setTimeout(() => {
          this.$router.go(-1);
        }, 1000);
      })
    },
  },
};
</script>

<style>
</style>
